package com.sfx.distributeLockStock.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.Verification;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: sfx
 * Date: 2024-01-24
 * Time: 9:45
 */
public class JWTUtils {
    private static final String SECRET = "sfx@";

    public static String createJwt(Map<String, String> params) {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, 3);
        JWTCreator.Builder builder = JWT.create();
        // 设置用户传的业务信息
        params.forEach(builder::withClaim);
        builder.withExpiresAt(calendar.getTime());

        return builder.sign(Algorithm.HMAC256(SECRET));
    }

    public static boolean verifyToken(String token) {
        try {
            JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
            jwtVerifier.verify(token);
        } catch (Throwable throwable) {
            System.out.println("校验失败");
            return false;
        }
        return true;
    }

    public static String parseJwt(String token, String key) {
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
        DecodedJWT verify = jwtVerifier.verify(token);
        return verify.getClaim(key).asString();
    }
}